{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "keras完整例子_2.ipynb",
      "version": "0.3.2",
      "provenance": [],
      "private_outputs": true,
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/yejianfeng2014/AI/blob/master/keras%E5%AE%8C%E6%95%B4%E4%BE%8B%E5%AD%90_2.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "metadata": {
        "id": "-DEYgW4moxwM",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "outputId": "e9488247-c4fc-4561-fb68-96f777625636"
      },
      "cell_type": "code",
      "source": [
        "import numpy as np\n",
        "import random\n",
        "import keras\n",
        "import matplotlib.pyplot as plt\n",
        "# %matplotlib inline\n",
        "\n",
        "from keras.datasets import mnist\n",
        "from keras.models import Sequential, Model\n",
        "from keras.layers.core import Dense, Dropout, Activation\n",
        "from keras.optimizers import RMSprop\n",
        "from keras.utils import np_utils\n"
      ],
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Using TensorFlow backend.\n"
          ],
          "name": "stderr"
        }
      ]
    },
    {
      "metadata": {
        "id": "wPlkTVrao5SP",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "\n",
        "(X_train, y_train), (X_test, y_test) = mnist.load_data()\n",
        "\n",
        "print(X_train.shape, y_train.shape)\n",
        "print(X_test.shape, y_test.shape)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "3Qzp9jrOpOvX",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "\n",
        "X_train = X_train.reshape(X_train.shape[0], -1)  # 等价于X_train = X_train.reshape(60000,784)\n",
        "X_test = X_test.reshape(X_test.shape[0], -1)  # 等价于X_test = X_test.reshape(10000,784)\n",
        "X_train = X_train.astype(\"float32\")\n",
        "X_test = X_test.astype(\"float32\")\n",
        "X_train /= 255\n",
        "X_test /= 255\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "Qfob39BRpTun",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "\n",
        "y_train = np_utils.to_categorical(y_train, num_classes=10)\n",
        "y_test = np_utils.to_categorical(y_test, num_classes=10)\n",
        "\n",
        "model = Sequential()\n",
        "model.add(Dense(512, input_shape=(784,)))\n",
        "model.add(Activation('relu'))\n",
        "model.add(Dropout(0.2))\n",
        "model.add(Dense(512))\n",
        "model.add(Activation('relu'))\n",
        "model.add(Dropout(0.2))\n",
        "model.add(Dense(10))\n",
        "model.add(Activation('softmax'))\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "X1cUbQk6pe7j",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "如果是在notebook 的环境下，不需要带print（）  就可以直接查看，如果再idea 编辑器里面需要带print()才可以显示 。显示当前构建的模型结构"
      ]
    },
    {
      "metadata": {
        "id": "qHP8MeA7pXKv",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "model.summary()\n",
        " "
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "KEjIhvXspbYx",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "model.compile(loss= 'categorical_crossentropy',optimizer = 'rmsprop',metrics= ['accuracy'])\n",
        "\n",
        "\n",
        "rmsprop = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "D0pp4lNRp-2I",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "history = model.fit(X_train, y_train, epochs=10, batch_size=128,\n",
        "                    verbose = 1, validation_data=[X_test, y_test])\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "pTwEo4EsqCp-",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "history.params"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "zi0LdQ0jqens",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "预测"
      ]
    },
    {
      "metadata": {
        "id": "-J5QuVJiqPsM",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "score = model.evaluate(X_test, y_test, verbose = 0)\n",
        "print('Test score:', score[0])\n",
        "print('Test accuracy:', score[1])\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "8IK6BBx6qc6N",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# 下面来看预测的部分，为此先输出一张测试图像：\n",
        "X_test_0 = X_test[0,:].reshape(1,784)\n",
        "y_test_0 = y_test[0,:]\n",
        "plt.imshow(X_test_0.reshape([28,28]))\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "9vEp03D4qk2I",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "pred = model.predict(X_test_0[:])\n",
        "print('Label of testing sample', np.argmax(y_test_0))\n",
        "print('Output of the softmax layer', pred[0])\n",
        "print('Network prediction:', np.argmax([pred[0]]))\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "VW3zXUjrqrTi",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        ""
      ],
      "execution_count": 0,
      "outputs": []
    }
  ]
}